package com.adouteam.simple.wechat.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

/**
 * 配置文件读取工具
 *
 * @author buxianglong
 */
public class PropertiesTool {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesTool.class);
    private static final String DEFAULT_PROPERTIES_FILE_NAME = "simple-wechat.properties";
    private static Properties properties;

    static {
        properties = readProperties(DEFAULT_PROPERTIES_FILE_NAME);
    }

    /**
     * 获取指定键对应的值
     *
     * @param key 键名
     * @return 值
     */
    public static String getValue(String key) {
        return properties.getProperty(key, "");
    }

    /**
     * 获取指定键对应的值，如果不存在，则返回默认值
     *
     * @param key          键名
     * @param defaultValue 默认值
     * @return 值
     */
    public static String getValue(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }

    /**
     * 获取配置键值对集合
     *
     * @return 键值对集合
     */
    public static Set<Object> keySet() {
        return properties.keySet();
    }

    /**
     * 从配置文件中读取配置
     *
     * @param propertiesFileName 配置文件名称
     * @return 配置属性
     */
    private static Properties readProperties(String propertiesFileName) {
        Properties properties = new Properties();
        try (InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream(propertiesFileName)) {
            properties.load(inputStream);
        } catch (Exception e) {
            logger.error("Failed to load properties", e);
        }
        return properties;
    }
}
